const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const data = require('../data');
const postSQL = require('../../db/postSQL')
const userSQL = require('../../db/userSQL')
const async = require('async')
let partitionList = data.partitionList;

router.post('/getpost', bodyParser.json(), (req, res) => {
    let partitionID = req.body["partitionID"];
    // 检查分区是否为空
    if (req.body["partitionID"] == undefined
        || req.body["partitionID"] == null
        || typeof req.body["partitionID"] != "number") {
        res.json({
            err: 1,
            message: '分区为空'
        })
    } else {
        postSQL.getpost(partitionID, (partitions, posts) => {
            if (partitions.length == 0) {
                res.json({
                    err: 1,
                    message: '分区不存在'
                })
            } else {
                var result = {
                    err: 200,
                    message: '成功获取帖子列表',
                    partitionID,
                    partitionName: partitions[0].partitionName,
                    postList: []
                }
                var getNameTasks = []   // 获取用户名
                var tempPostList = []
                posts.forEach(post => {
                    var tempPost = {
                        postID: post.postID,
                        postTitle: post.postTitle,
                        userID: post.postUserID,
                        userName: '',
                        postTime: post.postTime,
                        lastTime: post.postReplyTime,
                        replyNum: post.postRepCount
                    }
                    var getName = (done) => {
                        userSQL.getinfo(post.postUserID, (result) => {
                            tempPost.userName = result[0].userName
                            tempPostList.push(tempPost)
                            done(null, null)
                        })
                    }
                    getNameTasks.push(getName)
                });
                console.log('tasks:')
                console.log(getNameTasks)
                async.series(getNameTasks, function (err, results) {
                    console.log('get name finish')
                    if (err) console.log(err)
                    else {
                        result.postList = tempPostList
                        console.log(result)
                        res.json(result)
                    }
                })
            }
        })
    }
})

module.exports = router;